package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.dao.UserInfoDto;
import com.example.entity.UserInfo;
import com.example.exception.BaseException;
import com.example.model.R;
import com.example.service.UserInfoService;
import com.example.vo.UserInfoVo;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @CreateTime 2025-02-22
 * @Description 用户信息管理
 */

@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    /**
     * 新增用户
     * @param userInfoDto
     * @return
     */
    @PostMapping("/save")
    //localhost:8080/user/save
    public R saveOneUser(@RequestBody UserInfoDto userInfoDto){
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoDto,userInfo);

        UserInfo user = userInfoService.getByName(userInfo);

        if (user != null) {
            return R.fail("用户名已存在");
        }

        userInfoService.save(userInfo);
        return R.ok(null,"新增成功");
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    //localhost:8080/user/{id}
    public R deleteUserById(@PathVariable("id") Long id){
        userInfoService.removeById(id);
        return R.ok(null,"删除成功");
    }

    /**
     * 根据name更新用户
     * @param userInfoDto
     * @return
     */
    @PutMapping("/update")
    //localhost:8080/user/update
    public R updateUserByName(@RequestBody UserInfoDto userInfoDto){

        try {
            //name不能为空
            if (userInfoDto.getName().isBlank()){
                throw new IllegalArgumentException("姓名不能为空");
            }
            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(userInfoDto,userInfo);

            UserInfo user = userInfoService.getByName(userInfo);

            //不存在用户，新增
            if (user == null) {
                userInfoService.save(userInfo);
                return R.ok(null,"新增成功: " + userInfo.getName());
            }

            //存在用户，根据name更新
            LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<UserInfo>()
                    .eq(UserInfo::getName,userInfo.getName());
            userInfoService.update(userInfo,lambdaUpdateWrapper);

            return R.ok(null,"更新成功");
        }catch (IllegalArgumentException e){
            return R.ok(e.getMessage());
        }catch (Exception e){
            log.error("系统异常：{}", e.getMessage(),e);  // log.error("msg", e) 记录堆栈
            return R.fail(null,"系统繁忙，请稍后重试");
        }
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    //localhost:8080/user/{id}
    public R<UserInfoVo> getUserById(@PathVariable Long id){
        //UserInfoVo userInfoVo1 = userInfoService.selectUserByIdResultMap(id);  //自定义方法查询

        UserInfoVo userInfoVo2 = new UserInfoVo();
        UserInfo userInfo = userInfoService.getById(id);                       //mp方法查询
        BeanUtils.copyProperties(userInfo,userInfoVo2);

        //log.info("userInfoVo1 = " + userInfoVo1);
        log.info("userInfoVo2 = " + userInfoVo2);
        //return R.ok(userInfo1);
        return R.ok(userInfoVo2,"查询成功");
    }



    /**
     * 批量操作----------------------------------------------------------------------------------------------------------------
     */



    /**
     * 批量插入
     * @param userInfoDtoList
     * @return
     */
    @PostMapping("/saveBatch")
    @Transactional
    //localhost:8080/user/saveBatch
    public R saveUserBatch(@RequestBody List<UserInfoDto> userInfoDtoList){
        log.info("批量插入用户请求，数量：{}", userInfoDtoList.size());
        try{
            //参数校验
            if (CollectionUtils.isEmpty(userInfoDtoList)){
                log.warn("批量插入参数为空");
                return R.fail(null,"用户列表不能为空");
            }

            //数据处理
            List<UserInfo> userInfoList = userInfoDtoList.stream()
                    .map(dto -> {
                        UserInfo userInfo = new UserInfo();
                        BeanUtils.copyProperties(dto, userInfo);
                        return userInfo;
                    })
                    .collect(Collectors.toList());

            //插入前校验
            userInfoService.getCheckBatch(userInfoList);
            //批量插入
            boolean result = userInfoService.saveBatch(userInfoList);

            return result ? R.ok(null,"批量插入成功数量：" + userInfoList.size()) : R.fail(null,"批量插入失败");
        }catch (BaseException e){
            log.error("业务校验异常：{}", e.getMessage());
            return R.ok(e.getErrorCode(),e.getMessage());
        }catch (Exception e){
            log.error("系统异常：{}", e.getMessage(),e);  // log.error("msg", e) 记录堆栈
            return R.fail("系统繁忙，请稍后重试");
        }
    }

    /**
     * 根据名称批量删除
     * @param list
     * @return
     */
    //localhost:8080/user/deleteBatch
    @DeleteMapping("/deleteBatch")
    @Transactional
    public R deleteBatch(@RequestBody @NotEmpty List<String> list) {
        //使用QueryWrapper构建IN条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("name", list);

        //删除
        boolean isRemoved = userInfoService.remove(queryWrapper);

        return isRemoved ? R.ok(null,"批量删除成功，删除记录数：" + list.size()) : R.fail("删除失败，请检查参数");
    }

    /**
     * 根据名称批量更新
     * @param userInfoDtoList
     * @return
     */
    //localhost:8080/user/updateByBatchNm
    @PutMapping("/updateByBatchNm")
    @Transactional
    public R updateByBatchName(@RequestBody @NotEmpty  List<UserInfoDto> userInfoDtoList){

        //数据处理
        List<UserInfo> list = userInfoDtoList.stream()
                .map(dto ->{
                    UserInfo userInfo = new UserInfo();
                    BeanUtils.copyProperties(dto,userInfo);
                    return userInfo;
                }).collect(Collectors.toList());

        //批量更新
        for(UserInfo userInfo : list){
            LambdaUpdateWrapper<UserInfo> wrapper = new LambdaUpdateWrapper<UserInfo>()
                    .eq(UserInfo::getName,userInfo.getName());
            userInfoService.update(userInfo,wrapper);
        }

        return R.ok(null,"批量更新成功");
    }

    /**
     * 根据ids批量查询
     * @param ids
     * @return
     */
    @GetMapping
    //localhost:8080/user/{ids}
    public R<List<UserInfoVo>> getUserByIds(@RequestParam List<Long> ids){

        List<UserInfoVo> list = userInfoService.selectBatchByIds(ids);

        return R.ok(list,"查询成功");
    }

    /**
     * 批量、模糊查询
     * @param userInfoDto
     * @return
     */
    @PostMapping("/queryBatch")
    //localhost:8080/user/queryBatch
    public R<List<UserInfoVo>> getUserByLambdaQuery(@RequestBody UserInfoDto userInfoDto){

        List<UserInfoVo> list = userInfoService.queryBatch(userInfoDto);

        return R.ok(list,"查询成功");
    }
}
